package com.app.couponsharelife.utils

import com.google.gson.*
import java.lang.reflect.Type

/**
 *Created by xct on 2019/1/19
 *Description:
 */
class JsonUtil {
    private val gson = GsonBuilder()
            .setDateFormat("yyyy-MM-DD'T'HH:mm:ss")
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
            .registerTypeAdapter(Boolean::class.java, BooleanSerializer())
            .registerTypeAdapter(Boolean::class.javaPrimitiveType, BooleanSerializer())
            .create()

    fun <T> fromJson(json: String, classOfT: Class<T>): T {
        return gson.fromJson(json, classOfT)
    }

    fun <T> fromJson(json: String, typeOfT: Type): T {
        return gson.fromJson(json, typeOfT)
    }

    fun <T> fromJson(json: JsonElement, typeOfT: Type): T {
        return gson.fromJson(json, typeOfT)
    }

    fun toJson(src: Any): String {
        return gson.toJson(src)
    }


    internal class BooleanSerializer : JsonSerializer<Boolean>, JsonDeserializer<Boolean> {

        override fun serialize(arg0: Boolean?, arg1: Type, arg2: JsonSerializationContext): JsonElement {
            return JsonPrimitive(arg0!!)
        }

        @Throws(JsonParseException::class)
        override fun deserialize(arg0: JsonElement, arg1: Type, arg2: JsonDeserializationContext): Boolean? {
            val result: Boolean
            try {
                result = arg0.asInt == 1
            } catch (e: Exception) {
                return arg0.asBoolean
            }

            return result
        }
    }
}